package com.mchat.config;

import com.mchat.exceptions.CommonException;
import io.r2dbc.spi.R2dbcDataIntegrityViolationException;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ServerWebExchange;
import java.time.Instant;

@RestControllerAdvice
public class GlobalWebExceptionHandler {

//     处理通用异常
    @ExceptionHandler(Exception.class)
    public ProblemDetail handleGlobalException(Exception ex, ServerWebExchange exchange) {
        ex.printStackTrace();
        ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        problem.setTitle("服务器内部错误");
        problem.setDetail(ex.getMessage());
        problem.setProperty("path", exchange.getRequest().getPath().toString());
        problem.setProperty("timestamp", Instant.now());
        return problem;
    }

    // 处理自定义业务异常
    @ExceptionHandler(CommonException.class)
    public ProblemDetail handleBusinessException(CommonException ex, ServerWebExchange exchange) {
        ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        problem.setTitle("执行失败");
        problem.setProperty("path", exchange.getRequest().getPath().toString());
        problem.setDetail(ex.getMessage());
        problem.setProperty("timestamp", Instant.now());
        return problem;
    }
}